<?php

/**
 * Name: 用户控制器
 * User: Silent
 * Date: 2025-01-30
 * Time: 10:00:00
 */

namespace App\Http\Controllers\V1\Resources\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\UserRequest;
use App\Models\Auth\WechatUser;
use App\Models\Config\Employee;
use App\Repositories\Auth\WechatUserRepository;
use App\Repositories\Config\EmployeeRepository;
use App\Services\Avatar\AvatarService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;

class UserController extends Controller
{
    protected $wechatUserRepository;
    protected $employeeRepository;
    protected $avatarService;

    public function __construct(
        WechatUserRepository $wechatUserRepository,
        EmployeeRepository $employeeRepository,
        AvatarService $avatarService
    ) {
        $this->wechatUserRepository = $wechatUserRepository;
        $this->employeeRepository = $employeeRepository;
        $this->avatarService = $avatarService;
    }

    /**
     * 绑定微信用户与员工
     *
     * @param Request $request
     * @return array
     */
    public function bind(Request $request)
    {
        try {
            $inputs = $request->all();

            // 从中间件获取微信用户信息
            $wechatUser = $request->input('wechat_user');
            if (!$wechatUser) {
                return $this->_error('用户未登录或认证失败');
            }

            // 检查是否已经绑定过员工
            $existingEmployee = $this->employeeRepository->query()
                ->where('wechat_user_id', $wechatUser->id)
                ->first();

            if ($existingEmployee) {
                return $this->_error('该微信用户已绑定员工：' . $existingEmployee->name);
            }

            DB::beginTransaction();

            // 如果提供了员工ID，则绑定现有员工
            if (!empty($inputs['employee_id'])) {
                $employee = $this->employeeRepository->find($inputs['employee_id']);
                if (!$employee) {
                    DB::rollBack();
                    return $this->_error('员工不存在');
                }

                // 检查该员工是否已绑定其他微信用户
                if ($employee->wechat_user_id) {
                    DB::rollBack();
                    return $this->_error('该员工已绑定其他微信用户');
                }

                // 更新员工的微信用户ID，并同步公司和部门信息
                $employee->wechat_user_id = $wechatUser->id;
                $employee->company = $wechatUser->company ?? '';
                $employee->department = $wechatUser->department ?? '';
                $employee->save();

                // 生成并上传头像
                $avatarResult = $this->generateUserAvatar($employee->name, $employee->id);

                // 如果头像生成成功，更新微信用户头像URL
                if ($avatarResult['success']) {
                    $wechatUser->headimgurl = $avatarResult['url'];
                    $wechatUser->save();
                }

                DB::commit();

                $responseData = [
                    'employee' => $employee,
                    'wechat_user' => $wechatUser
                ];

                // 如果头像生成成功，添加头像信息到响应
                if ($avatarResult['success']) {
                    $responseData['avatar'] = [
                        'url' => $avatarResult['url'],
                        'generated' => true
                    ];
                }

                return $this->_success('绑定成功', $responseData);
            }

            // 如果没有提供员工ID，则创建新员工
            $employeeData = [
                'username' => $inputs['name'] ?? $wechatUser->nickname,
                'phone' => $inputs['phone'] ?? '',
                'email' => $inputs['email'] ?? '',
                'name' => $inputs['name'] ?? $wechatUser->nickname,
                'team' => $inputs['team'] ?? '',
                'team_id' => $inputs['team_id'] ?? '',
                'position' => $inputs['position'] ?? '',
                'job_id' => $inputs['job_id'] ?? '',
                'company' => $wechatUser->company ?? '',
                'department' => $wechatUser->department ?? '',
                'wechat_user_id' => $wechatUser->id,
            ];

            // 如果职务是主管/部长/副部长，则班组id设置为null，班组名称设置为"无"
            if (isset($employeeData['position']) && in_array($employeeData['position'], ['主管', '部长', '副部长'])) {
                $employeeData['team_id'] = null;
                $employeeData['team'] = '无';
            }

            // 创建新员工
            $employee = $this->employeeRepository->create($employeeData);

            // 生成并上传头像
            $avatarResult = $this->generateUserAvatar($employee->name, $employee->id);

            // 如果头像生成成功，更新微信用户头像URL
            if ($avatarResult['success']) {
                $wechatUser->headimgurl = $avatarResult['url'];
                $wechatUser->save();
            }

            DB::commit();
            Log::info('微信用户绑定员工成功', [
                'wechat_user_id' => $wechatUser->id,
                'employee_id' => $employee->id,
                'openid' => $wechatUser->openid,
                'avatar_generated' => $avatarResult['success'] ?? false
            ]);

            $responseData = [
                'employee' => $employee,
                'wechat_user' => $wechatUser
            ];

            // 如果头像生成成功，添加头像信息到响应
            if ($avatarResult['success']) {
                $responseData['avatar'] = [
                    'url' => $avatarResult['url'],
                    'generated' => true
                ];
            }

            return $this->_success('绑定成功', $responseData);
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('微信用户绑定员工失败', [
                'error' => $e->getMessage(),
                'wechat_user_id' => $wechatUser->id ?? null,
                'openid' => $wechatUser->openid ?? null
            ]);

            return $this->_error('绑定失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户绑定信息
     *
     * @param Request $request
     * @return array
     */
    public function getBindInfo(Request $request)
    {
        try {
            $openid = $request->input('openid');

            if (empty($openid)) {
                return $this->_error('openid不能为空');
            }

            // 查找微信用户
            $wechatUser = $this->wechatUserRepository->findByOpenid($openid);
            if (!$wechatUser) {
                return $this->_error('微信用户不存在');
            }

            // 查找绑定的员工
            $employee = $this->employeeRepository->query()
                ->where('wechat_user_id', $wechatUser->id)
                ->first();

            return $this->_success('获取成功', [
                'wechat_user' => $wechatUser,
                'employee' => $employee,
                'is_bound' => !empty($employee)
            ]);
        } catch (Exception $e) {
            Log::error('获取用户绑定信息失败', [
                'error' => $e->getMessage(),
                'openid' => $request->input('openid')
            ]);

            return $this->_error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 解除绑定
     *
     * @param Request $request
     * @return array
     */
    public function unbind(Request $request)
    {
        try {
            $openid = $request->input('openid');

            if (empty($openid)) {
                return $this->_error('openid不能为空');
            }

            // 查找微信用户
            $wechatUser = $this->wechatUserRepository->findByOpenid($openid);
            if (!$wechatUser) {
                return $this->_error('微信用户不存在');
            }

            // 查找绑定的员工
            $employee = $this->employeeRepository->query()
                ->where('wechat_user_id', $wechatUser->id)
                ->first();

            if (!$employee) {
                return $this->_error('未找到绑定的员工');
            }

            // 解除绑定
            $employee->wechat_user_id = null;
            $employee->save();

            Log::info('微信用户解除绑定成功', [
                'wechat_user_id' => $wechatUser->id,
                'employee_id' => $employee->id,
                'openid' => $openid
            ]);

            return $this->_success('解除绑定成功');
        } catch (Exception $e) {
            Log::error('解除绑定失败', [
                'error' => $e->getMessage(),
                'openid' => $request->input('openid')
            ]);

            return $this->_error('解除绑定失败：' . $e->getMessage());
        }
    }

    public function info(Request $request)
    {
        $userId = $request->input('user_id');
        $date = $request->input('date'); // 可选的日期参数，格式：Y-m-d

        // 如果用户未绑定员工，返回空数据
        if (!$userId) {
            return $this->_success('请求成功', [
                'info' => null,
                'count' => [
                    'riskCount' => 0,
                    'accidentCount' => 0,
                    'questionCount' => 0,
                    'hazardCount' => 0,
                    'thisMonthCheckIn' => 0,
                    'totalCheckIn' => 0,
                ],
                'unreadCount' => 0,
                'dutyLeaders' => [],
                'dutySupervisor' => null,
                'is_bound' => false
            ]);
        }

        $result = $this->employeeRepository->getUserInfoById($userId, $date);
        $result['is_bound'] = true;

        return $this->_success('请求成功', $result);
    }

    /**
     * 更新用户信息
     *
     * @param UserRequest $request
     * @return array
     */
    public function update(UserRequest $request)
    {
        try {
            $inputs = $request->validated();

            // 获取用户ID
            $userId = $request->input('user_id');
            if (!$userId) {
                return $this->_error('用户未登录或认证失败');
            }

            // 获取用户信息
            $userInfo = $this->employeeRepository->getUserInfoById($userId);
            if (!$userInfo || !$userInfo['info']) {
                return $this->_error('用户信息不存在');
            }

            $employee = $userInfo['info'];
            DB::beginTransaction();

            // 更新微信用户信息
            if (isset($inputs['headimgurl']) || isset($inputs['nickname'])) {
                $wechatUserData = [];
                if (isset($inputs['headimgurl'])) {
                    $wechatUserData['headimgurl'] = $inputs['headimgurl'];
                }

                if (!empty($wechatUserData) && $employee->wechat_user_id) {
                    $this->wechatUserRepository->update($employee->wechat_user_id, $wechatUserData);
                }
            }

            // 更新员工信息
            $employeeData = [];
            if (isset($inputs['name'])) {
                $employeeData['username'] = $inputs['name'];
            }
            if (isset($inputs['phone'])) {
                $employeeData['phone'] = $inputs['phone'];
            }
            if (isset($inputs['job'])) {
                $employeeData['position'] = $inputs['job'];
            }
            if (isset($inputs['job_id'])) {
                $employeeData['job_id'] = $inputs['job_id'];
            }
            if (isset($inputs['team'])) {
                $employeeData['team'] = $inputs['team'];
            }
            if (isset($inputs['team_id'])) {
                $employeeData['team_id'] = $inputs['team_id'];
            }

            // 如果职务是主管/部长/副部长，则班组id设置为null，班组名称设置为"无"
            if (isset($employeeData['position']) && in_array($employeeData['position'], ['主管', '部长', '副部长'])) {
                $employeeData['team_id'] = null;
                $employeeData['team'] = '无';
            }

            if (!empty($employeeData)) {
                $this->employeeRepository->update($employee->id, $employeeData);
            }

            DB::commit();

            // 获取更新后的用户信息
            $updatedUserInfo = $this->employeeRepository->getUserInfoById($userId);

            Log::info('用户信息更新成功', [
                'user_id' => $employee->id,
                'updated_fields' => array_keys($inputs)
            ]);

            return $this->_success('更新成功', $updatedUserInfo);
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('用户信息更新失败', [
                'error' => $e->getMessage(),
                'inputs' => $inputs ?? []
            ]);

            return $this->_error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 根据openid查询微信用户详情
     *
     * @param Request $request
     * @return array
     */
    public function getUserByOpenid(Request $request)
    {
        try {
            $openid = $request->input('openid');

            if (empty($openid)) {
                return $this->_error('openid不能为空');
            }

            // 查找微信用户及关联的员工信息
            $wechatUser = $this->wechatUserRepository->findByOpenid($openid);

            if (!$wechatUser) {
                return $this->_error('微信用户不存在');
            }
            Log::info('查询微信用户详情成功', [
                'openid' => $openid,
                'user_id' => $wechatUser->id
            ]);

            return $this->_success('查询成功', $wechatUser);
        } catch (Exception $e) {
            Log::error('查询微信用户详情失败', [
                'error' => $e->getMessage(),
                'openid' => $request->input('openid')
            ]);

            return $this->_error('查询失败：' . $e->getMessage());
        }
    }

    /**
     * 生成用户头像
     *
     * @param string $nickname 昵称
     * @param int $userId 用户ID
     * @return array
     */
    private function generateUserAvatar($nickname, $userId = null)
    {
        try {
            // 如果昵称为空，使用默认值
            if (empty($nickname)) {
                $nickname = '用户';
            }

            // 调用头像服务生成头像
            $result = $this->avatarService->generateAndUploadAvatar($nickname, $userId);

            Log::info('头像生成结果', [
                'nickname' => $nickname,
                'user_id' => $userId,
                'success' => $result['success'],
                'message' => $result['message']
            ]);

            return $result;

        } catch (Exception $e) {
            Log::error('头像生成异常', [
                'nickname' => $nickname,
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'url' => '',
                'message' => '头像生成异常：' . $e->getMessage()
            ];
        }
    }

    /**
     * 预览头像（API接口）
     *
     * @param Request $request
     * @return array
     */
    public function previewAvatar(Request $request)
    {
        try {
            $nickname = $request->input('nickname');

            if (empty($nickname)) {
                return $this->_error('昵称不能为空');
            }

            $result = $this->avatarService->previewAvatar($nickname);

            if ($result['success']) {
                return $this->_success('预览生成成功', [
                    'avatar_data' => $result['data'],
                    'nickname' => $nickname
                ]);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            Log::error('头像预览失败', [
                'nickname' => $request->input('nickname'),
                'error' => $e->getMessage()
            ]);

            return $this->_error('头像预览失败：' . $e->getMessage());
        }
    }

    /**
     * 获取头像服务状态
     *
     * @param Request $request
     * @return array
     */
    public function getAvatarServiceStatus(Request $request)
    {
        try {
            $status = $this->avatarService->getServiceStatus();

            return $this->_success('获取状态成功', $status);

        } catch (Exception $e) {
            return $this->_error('获取状态失败：' . $e->getMessage());
        }
    }
}
